import WebUploader from 'webuploader/dist/webuploader.js';
import PaBaseModel from '../../core/model/PaBaseModel.js';
import equipmentInspectionAdditionTpl from '../dialogs/equipmentInspectionAddition4Detail.html'; // 新增检测记录弹框
import equipmentAddMaintenanceRecordTpl  from '../dialogs/equipmentAddMaintenanceRecord.html'; // 新增维保记录弹框
import equipmentEditMaintanceRecordTpl from '../dialogs/equipmentEditMaintanceRecord.html'; // 编辑维保记录弹框
import equipmentSeeMaintanceRecordTpl from '../dialogs/equipmentSeeMaintanceRecord.html'; // 查看维保记录弹框

function equipmentInfoCtrl($scope, $http, ngDialog, fileUploaderService, paFetchService) {
  'ngInject';

  let _this = this;
  let id = $state.params.id;
  this.workerList = [];

  // 保存上传文件返回token
  this.acceptRecordToken = []; // 验收记录上传图片token

  this.equipmentInfo = {
    deviceName: '', // 设备名称
    innerNo: '', // 档案编号
    deviceModel: '', // 设备型号
    registrationNo: '', // 注册号
    license: '', // 拍照
    deviceLevel: '', // 设备等级
    operator: '', // 操作人员
    approachTime: '', // 进场时间
    exitTime: '', // 退场时间
    maintainSituation: '', // 维保情况
    isRented: '', // 是否租赁 0 否: 1 是
    accessoryFileBeans: [], // 检验记录图片
  }

  this.editableEquipmentInfo = new PaBaseModel(this.equipmentInfo);

  // 查询设备详细信息
  this.basedInformationQuery = () => {
    $http.get(`${SERVER_CONTEXT}/api/deviceinfo/queryDeviceDetail/${id}`)
      .then((resp) => {
        this.equipmentInfo = resp.data;
        if (!this.equipmentInfo.fileBeans) {
          this.equipmentInfo.fileBeans = [];
        }
        if (!this.equipmentInfo.accessoryFileBeans) {
          this.equipmentInfo.accessoryFileBeans = [];
        }
        // 处理人员名称
        this.handleData(this.equipmentInfo);
        this.editableEquipmentInfo = new PaBaseModel(this.equipmentInfo);
        // 获得施工队list
        paFetchService
          .getTeamWithOrgList()
          .then((resp) => {
            this.teamWithOrgList = resp.data;
            // 判断选中的人
            this.teamWithOrgList.forEach((org) => {
              org.teamList.forEach((team) => {
                this.getWorkersByTeamId(team);
              })
            })
          });
      });
  };

  // 处理人员、跳转到人员详细
  this.handleData = (param) => {
    if (param && param.operator && param.operatorId) {
      param.operator.split(',').forEach((item1, index1) => {
        param.operatorId.split(',').forEach((item2, index2) => {
          if (index2 == index1) {
            this.workerList.push({id: item2, name: item1});
          }
        });
      });
    }
  }

  this.basedInformationQuery();

  this.getWorkersByTeamId = (team) => {

    if (team.initFlag) {
      team.isShowWorker = !!!team.isShowWorker;
      return;
    }

    $http
      .get(`${SERVER_CONTEXT}/api/construction/select/${team.teamId}`)
      .then((resp) => {
        team.initFlag = true;
        team.workerInfoBeanList = resp.data;
        team.isShowWorker = !!!team.isShowWorker;

        if (this.equipmentInfo.operatorId) {
          this.equipmentInfo.operatorId.split(',').forEach((item) => {
            team.workerInfoBeanList.forEach((worker) => {
              if (worker.id == item) {
                worker.checked = true;
              }
            })
          })
        }

        // 判断是否全选
        team.checked = true;
        team.workerInfoBeanList.forEach((worker) => {
          if (!worker.checked){
            team.checked = false;
          }
        });
      })

  }

  // 根据施工队获得人员列表 added by sunqy
  this.showWorkers = (team) => {
    this.getWorkersByTeamId(team);
  }

  // 全选
  this.checkAll = function(selectTeam,$event){
    if (!selectTeam.workerInfoBeanList) {
      $http
        .get(`${SERVER_CONTEXT}/api/construction/select/${selectTeam.teamId}/${param.id}`)
        .then((resp) => {
          selectTeam.initFlag = true;
          selectTeam.workerInfoBeanList = resp.data;
          selectTeam.isShowWorker = !!!selectTeam.isShowWorker;
          selectTeam.workerInfoBeanList.forEach((worker) => {
            worker.constructionTeamName = selectTeam.teamName;
            worker.constructionTeamId = selectTeam.teamId;
            worker.checked = true;
          })
        })
    }

    var ele = $event.target;
    var flag = $(ele)[0].checked;
    if (flag) {
      selectTeam.isShowWorker = true;
    }
    $.each(this.teamWithOrgList,function(index,value){
      $.each(value.teamList,function(inx,team){
        if(team == selectTeam){
          $.each(team.workerInfoBeanList,function(ix,worker){
            worker.checked = flag;
          });
        }
      });
    });
  };

  // 判断全选人
  this.isChange = (id) => {
    var bool = true;
    this.teamWithOrgList.forEach((org) => {
      org.teamList.forEach((team) => {
        if (id == team.teamId) {
          team.workerInfoBeanList.forEach((item) => {
            if(!item.checked){
                bool = false;
            }
          })
          team.checked = bool;
        }
      })
    })
  }

  // 更新设备信息请求
  this.updateEquipInfo = (reload) => {
    $http.patch(`${SERVER_CONTEXT}/api/deviceinfo/updateDeviceInfo`, _this.editableEquipmentInfo)
      .then((resp) => {
        _this.editableEquipmentInfo.$sync();

        if(reload) $state.reload();
        _this.editable = false;
      });
  }

  // 基本信息按钮时间
  this.baseInfoEventHandler = {
    // 切换编辑状态
    toggleEditable: () => {
      // 取消按钮
      if (this.editable) {
        this.editableEquipmentInfo.$reset();
      }
      this.editable = !this.editable;
    },

    // 获得头像图片
    getAvatarSrc: () => {
      if (_this.equipmentInfo && _this.equipmentInfo.fileBean && _this.equipmentInfo.fileBean.filePath) {
        let src = `${SERVER_IP}/${_this.equipmentInfo.fileBean.filePath}`;
        return src;
      } else {
        return require('../../../assets/images/' + 'timg.jpg');
      }
    },

    // 保存设备基本信息
    save: (param) => {
      // 修改表单是否提交过状态
      param.$submitted = true;

      // 表单校验
      if (param.$invalid) {
        return false;
      }

      // 编辑操作人
      this.workerIds = [];
      this.workerNames = [];
      let tempTeams = {};
       $.each(this.teamWithOrgList,function(index,value){
        $.each(value.teamList,function(inx,team){
          $.each(team.workerInfoBeanList,function(ix,worker){
            if (worker.checked) {
              _this.workerIds.push(worker.id);
              _this.workerNames.push(worker.workerName);
            }
          });
        });
      });
      this.editableEquipmentInfo.operator = this.workerNames.join(',');
      this.editableEquipmentInfo.operatorId = this.workerIds.join(',');

      // 把文件上传返回token传入this.userInfo
      let imageToken = '';
      if (this.editableEquipmentInfo.fileBean) {
        imageToken = this.editableEquipmentInfo.fileBean.id;
      } else {
        imageToken = '';
      }
      this.editableEquipmentInfo.image = imageToken;
      // 文件
      this.editableEquipmentInfo.accessory = this.editableEquipmentInfo.accessoryFileBeans.map((item) =>{
        return item.id;
      }).join(',');
      this.updateEquipInfo(true);
    },

    // 重置
    reset: () => {
      this.editableEquipmentInfo.$reset();
    }
  }

  // 文件预览
  this.preview = (archiveDetail) => {
    let url = $state.href('documentPreview', {
      id: archiveDetail.id,
    });
    window.open(url,'_blank');
  }

  // 文件下载 ?? 接口
  this.getDownloadSrc = (file) => {
    return `${SERVER_CONTEXT}/api/safesite/workerInfo/download/${file.id}`;
  }

  // 验收记录
  this.acceptanceEditable = false;
  this.cancelEditAcceptance = () => {
    this.editableEquipmentInfo.$reset();
  }
  // 编辑
  this.toggleAcceptanceEditable = () => {
    if (this.acceptanceEditable) {
      this.cancelEditAcceptance();
      this.basedInformationQuery();
    }
    this.acceptanceEditable = !this.acceptanceEditable;
  }
  // 保存验收记录
  this.saveAcceptanceImage = () => {
    this.editableEquipmentInfo.inspectionRecords =
      this.editableEquipmentInfo
                                .fileBeans
                                .filter(item => item.id)
                                .map(item => item.id).join(',');
    this.updateEquipInfo();
    this.acceptanceEditable = false;
  }

  // 查询检测记录
  this.checkRecordList = [];
  this.queryCheckRecordData = () => {
    $http.post(`${SERVER_CONTEXT}/api/devicecheckrecord/queryCheckRecordList`, {"deviceId": id})
      .then((resp) => {
        this.checkRecordList = resp.data.data;
      });
  }
  this.queryCheckRecordData();

  // 获得图片路径
  this.getCheckRecordSrc = (file) => {
    if (file.filePath) {
      let src = `${SERVER_IP}/${file.filePath}`;
      return src;
    }
    return '';
  }

  // 新增检测记录
  this.addCheckRecord = function(){
    ngDialog.open({
      template: equipmentInspectionAdditionTpl,
      plain: true,
      className: 'ngdialog-theme-default pa-special-check-item-list-theme',
      controllerAs: 'addTextCode',
      controller: function($scope, $http) {
        'ngInject';
        this.addItem = {
          deviceId: id,
          fileBeans: [],
          deviceInfoBean: {
            id: id,
          },
        };
        this.attachments = [];
        this.submit = (param) => {
          // 修改表单是否提交过状态
          param.$submitted = true;
          // 表单校验
          if (param.$invalid) {
            return false;
          } else if(param.checkTime.$viewValue < param.nextChecktime.$viewValue) {
            // accessory 属性用于接收附件token 多个附件以逗号分隔
            this.addItem.accessory = this.attachments.map(item => item.id).join(',');
            $http.post(`${SERVER_CONTEXT}/api/devicecheckrecord/insertCheckRecord`,
                this.addItem)
                .then((resp) => {
                  if (resp.data.success) {
                    layer.msg(resp.data.message);
                    _this.queryCheckRecordData();
                    $scope.closeThisDialog();
                  } else {
                    layer.alert(resp.data.message);
                  }
                });
              } else {
                layer.alert('检测时间应小于下次检测时间');
              }

        }
      },
    });
  }

  // 删除检验记录
  this.deleteCheckRecord = (id) => {
    let _this = this;
    $scope.modalTitle = '删除检测记录';
    $scope.modalContent = '确认要删除该信息吗?';
    ngDialog.openConfirm({
    template: 'paConfirm',
    className: 'ngdialog-theme-default pa-confirm-theme',
    scope: $scope,
    }).
      then((value) => {
        $http.delete(`${SERVER_CONTEXT}/api/devicecheckrecord/deleteCheckRecord/${id}`)
              .then((resp) => {
                if (resp.data.success) {
                  layer.msg(resp.data.message);
                  _this.queryCheckRecordData();
                  // $scope.closeThisDialog();
                } else {
                  layer.alert(resp.data.message);
                }
              });
      }, (reason) => {});
  }

  // 新增维保记录query data
  // 获取维保记录列表info
  this.queryMaintainList = () => {
    $http.post(`${SERVER_CONTEXT}/api/devicemaintainrecord/selectMaintainRecordList`, {"deviceId": id})
      .then((resp) => {
        this.maintainRecordList = resp.data.data;
      });
  }
  this.queryMaintainList();

  // 新增维保记录
  this.addMainRecord = () => {
    ngDialog.open({
      template: equipmentAddMaintenanceRecordTpl,
      plain: true,
      className: 'ngdialog-theme-default pa-special-check-item-list-theme',
      controllerAs: 'vm',
      controller: function($scope, $http) {
        'ngInject';
        this.maintainRecordData = {
          deviceId: id, // 设备id
          deviceInfoBean: {
            id: id,
          },
          fileBeans: [], // 维保附件
          maintainTime: '', // 维保时间
          maintainContent: '' // 维保内容
        };

        // 新增维保记录
        this.submit = (param) => {
          // 修改表单是否提交过状态
          param.$submitted = true;
          // 表单校验
          if (param.$invalid) {
            return false;
          } else {
            // 维保文件
            this.maintainRecordData.accessory = this.maintainRecordData.fileBeans.map((item) => {
              return item.id;
            })
            this.maintainRecordData.accessory = this.maintainRecordData.accessory.join(',');

            $http.post(`${SERVER_CONTEXT}/api/devicemaintainrecord/insertMaintainRecord`,
              this.maintainRecordData)
              .then((resp) => {
                if (resp.data.success) {
                  layer.msg(resp.data.message);
                  _this.queryMaintainList();
                  $scope.closeThisDialog();
                } else {
                  layer.alert(resp.data.message);
                }
              });
          }

        }
      },
    });
  }

  // 查看維保记录
  this.seeMaintanceRecord = (param, index) => {
    ngDialog.open({
      template: equipmentSeeMaintanceRecordTpl,
      plain: true,
      className: 'ngdialog-theme-default pa-special-check-item-list-theme common-attachment-upload-outer',
      controllerAs: 'vm',
      controller: function($scope, $http) {
        'ngInject';
        let maintenanceId = param.id;

        // 获取维保信息
        this.getMaintanceInfo = () => {
          $http.get(`${SERVER_CONTEXT}/api/devicemaintainrecord/queryMaintainRecordInfo/${maintenanceId}`)
              .then((resp) => {
                if (resp.statusText == 'OK') {
                  this.maintainRecordData = resp.data;
                }
              });
        }

        this.getMaintanceInfo();

        // 文件预览
        this.preview = (archiveDetail) => {
          let url = $state.href('documentPreview', {
            id: archiveDetail.id,
          });
          window.open(url,'_blank');
        }

        // 文件下载 ?? 接口
        this.getDownloadSrc = (file) => {
          return `${SERVER_CONTEXT}/api/safesite/workerInfo/download/${file.id}`;
        }
      }
    });
  }

  // 编辑维保记录
  this.editMaintanceRecord = (param, index) => {
    ngDialog.open({
      template: equipmentEditMaintanceRecordTpl,
      plain: true,
      className: 'ngdialog-theme-default pa-special-check-item-list-theme common-attachment-upload-outer',
      controllerAs: 'vm',
      controller: function($scope, $http) {
        'ngInject';
        let maintenanceId = param.id;

        // 获取维保信息
        this.getMaintanceInfo = () => {
          $http.get(`${SERVER_CONTEXT}/api/devicemaintainrecord/queryMaintainRecordInfo/${maintenanceId}`)
              .then((resp) => {
                if (resp.statusText == 'OK') {
                  this.maintainRecordData = resp.data;
                  if (!this.maintainRecordData.fileBeans) {
                    this.maintainRecordData.fileBeans = [];
                  }
                }
              });
        }

        this.getMaintanceInfo();

        this.submitUpdate = (param) => {
          // 修改表单是否提交过状态
          param.$submitted = true;
          // 表单校验
          if (param.$invalid) {
            return false;
          } else {
            // accessory 属性用于接收附件token 多个附件以逗号分隔
            this.maintainRecordData.accessory = this.maintainRecordData.fileBeans.map((item) => {
              return item.id;
            });
            this.maintainRecordData.accessory = this.maintainRecordData.accessory.join(',');
            $http.patch(`${SERVER_CONTEXT}/api/devicemaintainrecord/updateMaintainRecord`, this.maintainRecordData)
                .then((resp) => {
                  if (resp.data.success) {
                    layer.msg(resp.data.message);
                    _this.queryMaintainList();
                    $scope.closeThisDialog();
                  } else {
                    layer.alert(resp.data.message);
                  }
                });

          }
        }
      }
    });
  }

  // 删除维保记录
  this.recordDetete = (item) => {
    $scope.modalTitle = '删除信息';
    $scope.modalContent = '确认要删除此信息吗?';
    ngDialog.openConfirm({
      template: 'paConfirm',
      className: 'ngdialog-theme-default pa-confirm-theme',
      scope: $scope,
    })
      .then((value) => {
         $http({
           method: 'DELETE',
           url: `${SERVER_CONTEXT}/api/devicemaintainrecord/deleteMaintainRecord/${item.id}`
         })
           .then((resp) => {
             if (resp.data.success) {
              layer.msg('删除成功');
              this.queryMaintainList();
             }
           });
      }, (reason) => {});
  }

}

export default equipmentInfoCtrl;